package com.seagate.app.servlet;

import com.seagate.app.manager.UserRole;
import com.seagate.app.bean.UserBean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.seagate.util.ldap.LdapBean;

import java.io.*;
//import com.seagate.app.user.ManageUser;
import java.util.Date;
//import java.util.List;
//import com.seagate.util.db.OracleConnect;

/**
 *
 * @author 407893
 */
public class LoginServlet extends HttpServlet {

  //private static Logger log = Logger.getLogger(LoginServlet.class);
  //private FileOcrInformation ocr = new FileOcrInformation();
  //private ManageUser user = new ManageUser();
  //private FileHGA hga = new FileHGA();
  //private static Logger log = Logger.getLogger("100__OCR_HGA_Process");
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
    PrintWriter out = response.getWriter();
    try {
      Date start_time = new Date();
      /* TODO output your page here
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet LoginServlet</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<h1>Servlet LoginServlet at " + request.getContextPath () + "</h1>");
      out.println("</body>");
      out.println("</html>");
       */
      // get input parameter
      //log.info("Connect Database.");
      //OracleConnect.connect();
      //OracleConnect.close();
      //log.info("Entering application.");
      //protect back
      //response.setHeader("Cache-Control", "no-cache"); //Forces caches to obtain a new copy of the page from the origin server

      //response.setHeader("Cache-Control", "no-store"); //Directs caches not to store the page under any circumstance

      //response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"

      //response.setHeader("Pragma", "no-cache"); //HTTP 1.0 backward compatibility

      String session_id = request.getRequestedSessionId();
      String user_id = request.getParameter("requiredGID");
      String password = request.getParameter("requiredPassword");
      String target = request.getParameter("target");
      /*if(request.getSession().isNew()){
      String returnPage = "/login.jsp";
      getServletContext().getRequestDispatcher(returnPage).forward(request, response);
      return ;
      }*/
      //log.info("user_id=" + user_id + " " + request.getSession().isNew());
      // get data from model in Java bean class
      LdapBean jlb = new LdapBean();
      //log.debug("jlb=" + jlb);
      //System.out.println("jlb="+jlb);
      boolean auth = false;
      if ((user_id != null) && (password != null)) {
        auth = jlb.authenticate(user_id, password);
      }

      //log.debug("auth=" + auth);
      //System.out.println("auth="+auth);
      String destination = "/";
      if (auth == false) {
        // try login again
        destination += "login.jsp?retry=" + jlb.getErrorMessage();
        if (jlb.getResultCode() == LdapBean.INVALID_PASSWORD) {
          destination += "&user_id=" + user_id;
        }
      } else {
        // return to caller
        if (target != null) {
          destination += target;
        //System.out.println("destination3="+destination);
        } else {
          destination += "home.jsp";
        //System.out.println("destination2="+destination);
        }
        //System.out.println("destination1="+destination);
        //List listFileName = ocr.getFileDescription(request.getSession().getServletContext().getInitParameter("pathFile"),user_id);
        //request.getSession().setAttribute("imageFile", listFileName);
        request.setAttribute("start_time", start_time);
        request.getSession().setAttribute("GID", user_id);
        UserRole lot = new UserRole();

        UserBean ub=lot.getUser(user_id);
        String userrole="User";
        if(ub!=null)
            userrole=ub.getRole();

        request.getSession().setAttribute("Roles", userrole);


        //System.out.println("Path = " + request.getContextPath());
//        String url = getUrl(request);
//        System.out.println("URL = " + url);
//        System.out.println("p = " + request.getPathInfo());
//        System.out.println("q = " + request.getQueryString());

      }

      response.sendRedirect("/AMA_Part_Management" + destination);
    //getServletConfig().getServletContext().getRequestDispatcher(destination).forward(request, response);
    } finally {
      out.close();
    //log.info("Exiting application.");
    }
  }

//  public String getUrl(HttpServletRequest req) {
//    String scheme = req.getScheme();             // http
//    String serverName = req.getServerName();     // hostname.com
//    int serverPort = req.getServerPort();        // 80
//    String contextPath = req.getContextPath();   // /mywebapp
//    //String servletPath = req.getServletPath();   // /servlet/MyServlet
//    String servletPath = "/viewReport.jsp";   // /servlet/MyServlet
//    //String pathInfo = req.getPathInfo();         // /a/b;c=123
//    //String queryString = req.getQueryString();          // d=789
//
//    // Reconstruct original requesting URL
//    String url = scheme + "://" + serverName + ":" + serverPort + contextPath + servletPath;
//    /*
//    if (pathInfo != null) {
//    url += pathInfo;
//    }
//    if (queryString != null) {
//    url += "?" + queryString;
//    }
//     */
//    return url;
//  }

  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  /**
   * Handles the HTTP <code>GET</code> method.
   * @param request servlet request
   * @param response servlet response
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }

  /**
   * Handles the HTTP <code>POST</code> method.
   * @param request servlet request
   * @param response servlet response
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }

  /**
   * Returns a short description of the servlet.
   */
  public String getServletInfo() {
    return "Short description";
  }// </editor-fold>
}
